<template>
  <div class="box">
    <div ref="redBox" class="top"></div>
    <div ref="whiteBox" class="start" :class="{ 'fixed': isFixed }" :style="whiteBoxStyle"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue';

const redBox = ref(null);
const whiteBox = ref(null);
const isFixed = ref(false);
const lastScrollTop = ref(0);

const checkPosition = () => {
  if (!redBox.value || !whiteBox.value) return;

  const redRect = redBox.value.getBoundingClientRect();
  const whiteRect = whiteBox.value.getBoundingClientRect();
  const currentScrollTop = window.pageYOffset || document.documentElement.scrollTop;

  // 判断滚动方向
  const isScrollingDown = currentScrollTop > lastScrollTop.value;

  // 计算黑色盒子底部位置（实际是红盒子，但样式定义为黑色）
  const blackBoxBottom = redRect.bottom + window.scrollY;

  if (whiteRect.top <= blackBoxBottom && isScrollingDown) {
    isFixed.value = true;
    console.log('固定', whiteRect.top, blackBoxBottom);
  } else if (isScrollingDown) {
    isFixed.value = false;
    console.log('取消固定', whiteRect.top, blackBoxBottom);
  } else if (!isScrollingDown && whiteRect.top > blackBoxBottom) {
    isFixed.value = false;
    console.log('取消固定', whiteRect.top, blackBoxBottom);
  }

  lastScrollTop.value = currentScrollTop;
};

const whiteBoxStyle = computed(() => {
  if (isFixed.value) {
    return {
      position: "sticky",
      top: '10vh',
      left: 0,
      zIndex: 1,
    };
  } else {
    return {
      position: 'absolute',
      top: '40vh',
      zIndex: 1,
    };
  }
});

onMounted(() => {
  window.addEventListener('scroll', checkPosition);
  // 初始检查
  checkPosition();
  console.log('组件已挂载，监听滚动事件');
});

onUnmounted(() => {
  window.removeEventListener('scroll', checkPosition);
});
</script>

<style scoped>
.box {
  width: 100vw;
  height: 200vh;
  background-color: skyblue;
  top: 0;
  left: 0;
  position: relative;
}

.top {
  position: sticky;
  width: 100vw;
  height: 10vh;
  background-color: #000;
  z-index: 2;
  top: 0;
}

.start {
  width: 100vw;
  height: 30vh;
  background-color: #fff;
  z-index: 1;
  position: sticky;
  /* 如果你用动态 style 可以不在这里写具体的 top 值 */
}

.fixed {
  /* 类和动态 style 中设置的属性可能会冲突，建议保持一致 */
  position: fixed;
  top: 10vh;
  left: 0;
  z-index: 1;
}
</style>
